/**
 * Created by shudong.msd(风骐) on 2016/4/17.
 */


app.factory("resultDataFetcher",['$http','$rootScope','$q','$timeout','$window','$state',function($http,$rootScope,$q,$timeout,$window,$state){

    var service = {};

    var comutil = new commUtils();

    // 观察者模式
    var scopes = [];

    service.registScope = function(scope){
        for(var i in scopes){
            if(scopes[i].myName==scope.myName){
                // 删去旧的scope
                scopes.splice(i,1);
                break;
            }
        }
        scopes.push(scope);
    };

    var searchPromise = function(data,type){

        var deferred = $q.defer();

        var tmpUrl = '';
        if(data['taskId']!=undefined){
            tmpUrl= UrlMappings.SEARCH_FROM_MISSION;
            $http({
                method  : 'POST',
                url     : tmpUrl,
                params : {
                    'access_token':comutil.getTocken(),
                    'taskId':data['taskId'],
                    'pageNo':data['pageNo'],
                    'pageSize':data['pageSize']
                },
                headers : {
                    'Accept':'application/json',
                    'Content-Type': 'application/json'
                }
            }).success(function (data) {
                deferred.resolve(data)
            }).error(function(data,status) {
                if(status=='401')comutil.logout($state);
                deferred.reject(data);
            });

            return deferred.promise;

        }else if(data.queryType==0||data.queryType==1){
            tmpUrl= UrlMappings.VAGUE_SEARCH(type);
        }else{
            tmpUrl= UrlMappings.ACCURATE_SEARCH;
        }

        $http({
            method  : 'POST',
            url     : tmpUrl,
            data    : data,
            params : {
                'access_token':comutil.getTocken()
            },
            headers : {
                'Accept':'application/json',
                'Content-Type': 'application/json'
            }
        }).success(function (data) {
            deferred.resolve(data)
        }).error(function(data,status) {
            if(status=='401')comutil.logout($state);
            deferred.reject(data);
        });

        return deferred.promise;
    };


    service.initData = function(type){
        $rootScope.isLoading = true;
        historyData = {};//本次查询历史置空
        var tData = comutil.getSearchData();

        $rootScope.newMissionType = tData['queryType'];

        //查询
        var p = searchPromise(tData,type);
        p.then(function(data){
            updateAllData(data,type,1000);
        });

    };

    var updateAllData = function(data,type,delayTime){
        $timeout(function(){
            var dgOverLoading = false;
            var searchD = comutil.getSearchData();
            for(var i in scopes){
                if(scopes[i].myName=='FilterBox'){
                    if(searchD.queryType==0||searchD.queryType==1){
                        if(data['otherData']==null){
                            scopes[i].changeCollapseShow();
                            initProType(scopes[i]);
                            dgOverLoading = true;
                            continue;
                        }
                        initFilters(scopes[i],type,data['otherData']);
                    }else{
                        if(searchD['taskId']!=undefined){
                            scopes[i].changeCollapseShow();
                            initProType(scopes[i]);
                            dgOverLoading = true;
                            continue;
                        }
                        transformAccurateDataAndInit(data['otherData'],type,scopes[i]);
                    }

                }else if(scopes[i].myName=='DataGrid'){
                    if(searchD['taskId']!=undefined){
                        scopes[i].isMzSortable = false;
                    }
                    dealData(scopes[i],data,dgOverLoading);
                    scopes[i].initDom();
                }
            }

        },delayTime);
    };


    var transformAccurateDataAndInit = function(data,type,scope){
        if(data==null)data = {'queryParams':[]};
        $http.get(UrlMappings.SEARCH_PARAM_DEFAULT(type),{
            params : {
                'access_token':comutil.getTocken()
            },
            headers: {
                'Accept':'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function (defaultData) {
            data['queryParams']['terminal'] = defaultData['terminal'];
           // data['queryParams']['channel'] = defaultData['channel'];
            data['queryParams']['sex'] = defaultData['sex'];
            data['queryParams']['age'] = defaultData['age'];
            data['queryParams']['region'] = defaultData['region'];

            //城市model show
            scope.isCityModalShow = true;

            initFilters(scope,type,data);

            if(!scope.$$phase) {
                scope.$apply();
            }
        }).error(function(data,status){
            if(status=='401')comutil.logout($state);
        });;


        //受众地域初始化
        if($.isEmptyObject(cityInfo)){
            $http.get(UrlMappings.REGION_RESOURCE_LIST,{
                params : {
                    'access_token':comutil.getTocken()
                },
                headers: {
                    'Accept':'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function (data) {
                cityInfo = data;
                scope['hotCities'] = data['hotCities'][''];
                scope['baseProviceCities'] = data['province'][''];
                scope['alphCities'] = data['city'];

                if(!scope.$$phase) {
                    scope.$apply();
                }
            }).error(function(data,status){
                if(status=='401')comutil.logout($state);
            });;
        }else{
            scope['hotCities'] = cityInfo['hotCities'][''];
            scope['baseProviceCities'] = cityInfo['province'][''];
            scope['alphCities'] = cityInfo['city'];
        }

    };



    var initProType = function(scope){
        var tttype = comutil.getSearchData();
        if(tttype['queryType']==0){
            scope['programType'] = '电视剧';
        }else if(tttype['queryType']==1){
            scope['programType'] = '综艺节目';
        }else if(tttype['queryType']==2){
            scope['programType'] = '电视剧精准';
        }else if(tttype['queryType']==3){
            scope['programType'] = '综艺节目精准';
        }else if(tttype['queryType']==4){
            scope['programType'] = '明星参演电视剧';
        }else if(tttype['queryType']==5){
            scope['programType'] = '明星参演综艺节目';
        }

    };

    service.getQueryType = function(){
        return  comutil.getSearchData()['queryType'];
    };

    //缓存城市信息
    var cityInfo = {};

    //顺序不能变
    var filterTypes = ['timeRange','tvTypes','tvNames','stars','terminals','channels','languages','regions','sex','ages','cities'];

    var initFilters = function(scope,programType,data){

        // 初始化数据结构
        if(programType=='tv'){
            service.tvTypes.itemType = '电视剧类型';
            service.tvNames.itemType = '电视剧名称';
        }else{
            service.tvTypes.itemType = '综艺节目类型';
            service.tvNames.itemType = '综艺节目名称';
        }

        for(var i in filterTypes){
            scope[filterTypes[i]] = angular.copy(service[filterTypes[i]]);
        }

        var tttype = comutil.getSearchData();
        if(tttype['queryType']==0){
            scope['programType'] = '电视剧';
        }else if(tttype['queryType']==1){
            scope['programType'] = '综艺节目';
        }else if(tttype['queryType']==2){
            scope['programType'] = '电视剧精准';
        }else if(tttype['queryType']==3){
            scope['programType'] = '综艺节目精准';
        }else if(tttype['queryType']==4){
            scope['programType'] = '明星参演电视剧';
        }else if(tttype['queryType']==5){
            scope['programType'] = '明星参演综艺节目';
        }

        // 加载数据
        data = comutil.transcateData(data['queryParams']);

        // 非空元素
        var notNullItems = [];

        for(var i in filterTypes){
            if(filterTypes[i]=='tvNames'||filterTypes[i]=='stars'||filterTypes[i]=='cities'){
                if(data[filterTypes[i]]==undefined||data[filterTypes[i]]==null){
                    scope[filterTypes[i]].list = [];
                }else{
                    scope[filterTypes[i]].list = data[filterTypes[i]][''];
                }

                scope[filterTypes[i]].alphabetList['全部'] = scope[filterTypes[i]].list;

                //按字母分类
                for(var key in data[filterTypes[i]]){
                    if(key=="")continue;
                    scope[filterTypes[i]].alphabetList[key] = data[filterTypes[i]][key];
                }

                if(scope[filterTypes[i]].list!=undefined&&scope[filterTypes[i]].list.length>=35){
                    scope[filterTypes[i]].heightEnough = true;
                }

            }else{
                scope[filterTypes[i]].list = data[filterTypes[i]];
            }

            if(scope[filterTypes[i]].list!=undefined){
                if(scope[filterTypes[i]].list.length>=35){
                    scope[filterTypes[i]].isSpreadShow = true;
                }

                if(scope[filterTypes[i]].list.length>0)notNullItems.push(filterTypes[i]);
            }

        }

        //隐藏超过5个的元素
        if(notNullItems.length>5){
            for(var i=5;i<notNullItems.length;i++){
                scope.collapseItems.push(notNullItems[i]);
                scope[notNullItems[i]].isItemShow = false;
            }
        }
        scope.changeCollapseShow();

        //执行数据加载完后的dom操作
        scope.initDom();

        //至此初始化才算完成
        $rootScope.isLoading = false;
    };

    var dealData = function(scope,data,dgOverLoading){
        scope.gridOptions.totalItems = data['recordCount'];
        //var firstRow = (params.pageNumber - 1) * scope.gridOptions.paginationPageSize;
        //options.data = data.slice(firstRow, firstRow + scope.gridOptions.paginationPageSize);

        //处理日期
        for(var i in data['datas']){
            if(data['datas'][i].time.indexOf('-')>=0){
                var tmpId = data['datas'][i].time;
                var tmpName = tmpId.substring(0,4)+'/'+tmpId.substring(4,6)+'/'+tmpId.substring(6,8)+'~'+tmpId.substring(13,15)+'/'+tmpId.substring(15,17);
                data['datas'][i].time = tmpName;
            }else{
                var tmpId = data['datas'][i].time;
                var tmpName = tmpId.substring(0,4)+'/'+tmpId.substring(4,6)+'/'+tmpId.substring(6,8);
                data['datas'][i].time = tmpName;
            }
        }

        scope.gridOptions.data = data['datas'];

        var isStarHide = true;
        if(data['datas'].length>0&&data['datas'][0].star!=null){
            isStarHide = false;
        }

        if(isStarHide){
            for(var i in scope.gridOptions.columnDefs){
                if(scope.gridOptions.columnDefs[i].field=='star'){
                    scope.gridOptions.columnDefs[i].visible = false;
                    break;
                }
            }
        }

        if(dgOverLoading)$rootScope.isLoading = false;

    };

    service.freshData = function(scope,params,type){

        var tmpParms = {};

        //加入历史过滤选项
        if($.isEmptyObject(historyData)){
            tmpParms = angular.copy(comutil.getSearchData());
        }else{
            tmpParms = historyData;
        }

        tmpParms.pageNo = params.pageNo;
        tmpParms.pageSize = params.pageSize;
        tmpParms.sort = params.sort;

        var p = searchPromise(tmpParms,type);

        p.then(function(data){
            dealData(scope,data,false);
            if(!scope.$$phase) {
                scope.$apply();
            }
        });
    };


    var historyData = {};
    var lastFormData = [];

    service.updateFiltersToData=function(formData,type){

        var tmpParms = angular.copy(comutil.getSearchData());

        var notUpdateField = [];
        for(var key in formData){
            if(formData[key]!=undefined&&formData[key].length>0){
                notUpdateField.push(key);
            }
        }
        //找出这次提交里没有在上次提交中出现的，表示删除了一个选项，加入这次notupdate
        var diff = [];
        for(var i in lastFormData){
            if($.inArray(lastFormData[i],notUpdateField)==-1){
                diff.push(lastFormData[i]);
            }
        }
        //将这次提交表单保存成上次的
        lastFormData = angular.copy(notUpdateField);
        for(var i in diff){
            notUpdateField.push(diff[i]);
        }

        var tmpSub = comutil.recDatatoSubmit(formData);

        for(var key in tmpSub){
            if(tmpSub[key]!=undefined&&tmpSub[key].length>0){
                tmpParms[key] = tmpSub[key];
            }
        }
        if(tmpSub['timeRange']!=undefined&&tmpSub['timeRange'].length>0){
            delete tmpParms['startTime'];
            delete tmpParms['endTime'];
        }


        //存储历史纪录
        historyData = tmpParms;

        var p = searchPromise(tmpParms,type);
        p.then(function(data){
            //更新过滤项
            for(var i in scopes){
                if(scopes[i].myName=='FilterBox'){
                    if(tmpParms.queryType==0||tmpParms.queryType==1){
                        updateFFilters(scopes[i],type,data['otherData'],notUpdateField);
                    }else{
                        updateAccurateDataAndInit(data['otherData'],type,scopes[i],notUpdateField);
                    }

                }else if(scopes[i].myName=='DataGrid'){
                    dealData(scopes[i],data,false);
                }
            }
            if(!scopes[i].$$phase) {
                scopes[i].$apply();
            }

        });

        /*var p = searchPromise(tmpParms,type);
        p.then(function(data){
            for(var i in scopes){
                if(scopes[i].myName=='DataGrid'){
                    dealData(scopes[i],data,false);
                    if(!scopes[i].$$phase) {
                        scopes[i].$apply();
                    }
                }
            }
        });*/

    };


    var updateFFilters = function(scope,programType,data,notUpdateField){


        // 加载数据
        data = comutil.transcateData(data['queryParams']);

        for(var i in filterTypes){
            if($.inArray(filterTypes[i],notUpdateField)!=-1)continue;

            if(filterTypes[i]=='tvNames'||filterTypes[i]=='stars'||filterTypes[i]=='cities'){
                if(filterTypes[i]=='stars'&&data['stars']==null){
                    scope['stars'].list = [];
                }else{
                    scope[filterTypes[i]].list = data[filterTypes[i]][''];
                }

                scope[filterTypes[i]].alphabetList['全部'] = scope[filterTypes[i]].list;

                //按字母分类
                for(var key in data[filterTypes[i]]){
                    if(key=="")continue;
                    scope[filterTypes[i]].alphabetList[key] = data[filterTypes[i]][key];
                }

                if(scope[filterTypes[i]].list!=undefined&&scope[filterTypes[i]].list.length>=35){
                    scope[filterTypes[i]].heightEnough = true;
                }else{
                    scope[filterTypes[i]].heightEnough = false;
                }

            }else{
                scope[filterTypes[i]].list = data[filterTypes[i]];
            }

            if(scope[filterTypes[i]].list!=undefined){
                if(scope[filterTypes[i]].list.length>=35){
                    scope[filterTypes[i]].isSpreadShow = true;
                }else{
                    scope[filterTypes[i]].isSpreadShow = false;
                }

            }

        }

    };

    var updateAccurateDataAndInit = function(data,type,scope,notUpdateField){
        if(data==null)data = {'queryParams':[]};
        $http.get(UrlMappings.SEARCH_PARAM_DEFAULT(type),{
            params : {
                'access_token':comutil.getTocken()
            },
            headers: {
                'Accept':'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function (defaultData) {
            data['queryParams']['terminal'] = defaultData['terminal'];
            // data['queryParams']['channel'] = defaultData['channel'];
            data['queryParams']['sex'] = defaultData['sex'];
            data['queryParams']['age'] = defaultData['age'];
            data['queryParams']['region'] = defaultData['region'];

            updateFFilters(scope,type,data,notUpdateField);

        }).error(function(data,status){
            if(status=='401')comutil.logout($state);
        });;


        //受众地域初始化
        if($.isEmptyObject(cityInfo)){
            $http.get(UrlMappings.REGION_RESOURCE_LIST,{
                params : {
                    'access_token':comutil.getTocken()
                },
                headers: {
                    'Accept':'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function (data) {
                cityInfo = data;
                scope['hotCities'] = data['hotCities'][''];
                scope['baseProviceCities'] = data['province'][''];
                scope['alphCities'] = data['city'];

                if(!scope.$$phase) {
                    scope.$apply();
                }
            }).error(function(data,status){
                if(status=='401')comutil.logout($state);
            });
        }else{
            scope['hotCities'] = cityInfo['hotCities'][''];
            scope['baseProviceCities'] = cityInfo['province'][''];
            scope['alphCities'] = cityInfo['city'];
        }

    };


    service.dumpToExcelWithHistoryOptions = function(){
        var tmpDData = comutil.getSearchData();
        if(tmpDData['taskId']!=undefined){
            $window.location.href=UrlMappings.EXPORT_EXCEL_BY_ID+tmpDData['taskId']+'?access_token='+comutil.getTocken();
            return;
        }


        var tmpD = {};

        //加入历史过滤选项
        if($.isEmptyObject(historyData)){
            tmpD = comutil.getSearchData();
        }else{
            tmpD = historyData;
        }

        var $form = angular.element('<form>');
        var url = UrlMappings.EXPORT_EXCEL_HOT+'?access_token='+comutil.getTocken();
        var $input = angular.element('<input>');
        $input.attr('name','q');
        $input.attr('value',JSON.stringify(tmpD));
        $form.append($input);
        $form.attr('method','post');
        $form.attr('action',url);
        $form.hide();
        angular.element('body').append($form);
        $form.submit();
        $form.remove();

    };

    service.timeRange = {
        itemType:"日期范围",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };


    service.terminals = {
        itemType:"终端",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };

    service.channels = {
        itemType:"渠道",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };


    service.languages = {
        itemType:"语言",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        isItemSubmitted:false,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };


    service.regions = {
        itemType:"地区",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        isItemSubmitted:false,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };

    service.sex = {
        itemType:"受众性别",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        isItemSubmitted:false,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };

    service.ages = {
        itemType:"受众年龄",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        isItemSubmitted:false,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };

    service.tvTypes = {
        itemType:"电视剧类型",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        heightEnough: false,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };


    service.tvNames = {
        itemType:"电视剧名称",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        heightEnough: false,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };

    service.tvNames.alphabetList = {
        '全部':[]
    };



    service.stars = {
        itemType:"明星",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        heightEnough: false,
        isItemSubmitted:false,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };
    //明星详细
    service.stars.alphabetList = {   // 分字母
        '全部':[]
    };



    service.cities = {
        itemType:"受众地域",
        isCheckBoxShow:false,
        isItemShow:true,
        submitDisable:true,
        heightEnough: false,
        isItemSubmitted:false,
        isSpreadShow:false,
        isItemSpread:false,
        list:[]
    };

    // 城市详细
    service.cities.alphabetList = {
        '全部':[]
    };


    return service;
}]);

